//
//  UIColor+Extension.swift
//  SmartEyeForPatient
//
//  Created by QDSG on 2021/4/2.
//

import Foundation
import UIKit

extension UIColor {
    func image() -> UIImage {
        let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(self.cgColor)
        context?.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image ?? UIImage()
    }
    
    convenience init(hex: String) {
        let colorString: String = hex.replacingOccurrences(of: "#", with: "").uppercased()
        var alpha: CGFloat = 1.0, red: CGFloat = 0.0, green: CGFloat = 0.0, blue: CGFloat = 0.0
        
        switch colorString.count {
        case 3: /// RGB
            alpha = 1.0
            red = UIColor.colorComponent(fromString: colorString, range: 0..<1)
            green = UIColor.colorComponent(fromString: colorString, range: 1..<2)
            blue = UIColor.colorComponent(fromString: colorString, range: 2..<3)
        case 4: /// ARGB if irstIsAlpha is true, otherwise RGBA.
            red = UIColor.colorComponent(fromString: colorString, range: 0..<1)
            green = UIColor.colorComponent(fromString: colorString, range: 1..<2)
            blue = UIColor.colorComponent(fromString: colorString, range: 2..<3)
            alpha = UIColor.colorComponent(fromString: colorString, range: 3..<4)
        case 6: /// RRGGBB
            alpha = 1.0
            red = UIColor.colorComponent(fromString: colorString, range: 0..<2)
            green = UIColor.colorComponent(fromString: colorString, range: 2..<4)
            blue = UIColor.colorComponent(fromString: colorString, range: 4..<6)
        case 8: /// AARRGGBB if irstIsAlpha is true, otherwise RRGGBBAA.
            red = UIColor.colorComponent(fromString: colorString, range: 0..<2)
            green = UIColor.colorComponent(fromString: colorString, range: 2..<4)
            blue = UIColor.colorComponent(fromString: colorString, range: 4..<6)
            alpha = UIColor.colorComponent(fromString: colorString, range: 6..<8)
        default:
            break
        }
        
        self.init(red:red, green:green, blue:blue, alpha:alpha)
    }
    
    private static func colorComponent(fromString string: String, range: Range<Int>) -> CGFloat {
        let substring: String = string.substring(with: range)
        let fullHex = (range.upperBound - range.lowerBound) == 2 ? substring : "\(substring)\(substring)"
        var hexComponent: CUnsignedInt = 0
        Scanner(string: fullHex).scanHexInt32(&hexComponent)
        
        return CGFloat(hexComponent) / 255.0
    }
}

extension UIColor {
    static var background: UIColor { Asset.background.color }
}
